<template>
  <el-dialog :model-value="visible" title="参会人管理" width="700px" @close="$emit('update:visible', false)">
    <div v-if="meeting" class="space-y-2">
      <div class="flex justify-between items-center mb-2">
        <el-input v-model="search" placeholder="搜索参会人" clearable :prefix-icon="Search" style="width: 180px;"
          size="small" />
        <div class="flex items-center gap-2 input-card" v-if="type !== 'ended' && meeting.statusDesc !== '已结束' && meeting.statusDesc !== '已取消'">
          <el-button type="primary" size="small" @click="showSelectDialog = true">
            <CirclePlus class="icon-sm" /> 添加参会人
          </el-button>
        </div>
      </div>
      <el-table :data="participants" style="width: 100%" size="small" border max-height="320"
        class="rounded-table shadow-table" highlight-current-row v-loading="loading">
        <el-table-column prop="userName" label="姓名" />
        <el-table-column prop="orgName" label="组织机构" />
        <el-table-column prop="mobile" label="联系方式" />
        <el-table-column label="操作" width="100" v-if="type !== 'ended' && meeting.statusDesc !== '已结束' && meeting.statusDesc !== '已取消' && meeting.uid == userInfo.uid">
          <template #default="{ row }">
            <el-button size="small" type="danger" @click="removeParticipant(row)">
              <Remove class="icon-sm" /> 移除 
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div class="flex justify-center mt-4 pt-2 border-t border-dashed border-gray-200">
        <el-pagination background layout="prev, pager, next" :total="participants.length" :page-size="pageSize"
          v-model:current-page="currentPage" small />
      </div> -->

      <!-- 用户选择弹框 -->
      <UserSelectDialog v-if="showSelectDialog" v-model:visible="showSelectDialog" @confirm="handleUserSelected" />
    </div>
    <template #footer>
      <el-button @click="$emit('update:visible', false)">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { Search, User, CirclePlus, Remove } from '@element-plus/icons-vue'
import { getParticipantList, postAddParticipant, postRemoveParticipant } from '@/axios/api/meeting'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserSelectDialog from '@/components/UserSelectDialog/index.vue'
import { getUserInfo } from '@/utils/webStorage'
const userInfo = getUserInfo()

const props = defineProps({
  visible: Boolean,
  meeting: Object,
  type: String,
})
const search = ref('')
const participants = ref([])
const currentPage = ref(1)
const pageSize = 10
const loading = ref(false)

const showSelectDialog = ref(false)

watch(() => props.meeting, (val) => {
  if (val) {
    search.value = '' // 重置搜索
    currentPage.value = 1
    fetchParticipants()
  }
})



// 获取参会人员列表
async function fetchParticipants() {
  if (!props.meeting?.id) return

  try {
    loading.value = true
    const response = await getParticipantList({ meetingId: props.meeting.id, username: search.value.trim() })
    if (response.code === 0) {

      participants.value = response.result || []
      console.log(response.result);

    }
  } catch (error) {
    console.error('获取参会人员列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 监听搜索输入变化，实时调用接口
watch(search, (newValue) => {
  if (props.meeting?.id) {
    fetchParticipants()
  }
}, { debounce: 300 }) // 防抖300ms

// const pagedParticipants = computed(() => {
//   const start = (currentPage.value - 1) * pageSize
//   return participants.value.slice(start, start + pageSize)
// })

async function removeParticipant(row) {
  try {
    await ElMessageBox.confirm(
      `确定要移除参会人"${row.userName}"吗？`,
      '确认移除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await postRemoveParticipant({
      meetingId: props.meeting.id,
      uid: row.uid
    })

    if (response.code === 0) {
      ElMessage.success('移除参会人成功')
      fetchParticipants() // 重新获取列表
    } else {
      ElMessage.error(response.msg || '移除参会人失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('移除参会人失败:', error)
    }
  }
}

// 处理用户选择完成
const handleUserSelected = async (selectedUsers) => {
  if (!selectedUsers?.length) {
    ElMessage.warning('请选择参会人')
    return
  }

  try {
         // 获取选中的用户列表
        const selectedUserList = selectedUsers.map(
          (user) => ({
            uid: user.uid,
            userName: user.username,
          })
        );

       const res = await postAddParticipant({
          meetingId: props.meeting.id,
          userList: selectedUserList,
        })

        if (res && res.code === 0) {
          ElMessage.success('添加参会人成功')
          showSelectDialog.value = false
        } else {
          ElMessage.error('部分用户添加失败')
        }
      } catch (error) {
        console.error("添加参会人员失败:", error);
      } finally {
        console.log("finally")
        fetchParticipants() // 刷新列表
      }
}
</script>

<style scoped>
.input-card {
  background: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  border-radius: 8px;
  padding: 8px 16px;
}

.el-table.rounded-table {
  background: #f8f9fa;
  border-radius: 10px;
  overflow: hidden;
}

.shadow-table {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
}

.el-table .el-table__row:hover {
  background: #f0f6ff !important;
}

.flex {
  display: flex;
}

.gap-2 {
  gap: 8px;
}

.icon-sm {
  width: 16px;
  height: 16px;
  font-size: 16px;
  vertical-align: middle;
  margin-right: 2px;
}
</style>
